import React, { useState, useEffect, useRef } from 'react';
import { baseUrl } from '@/assets/baseUrl'
import { SmileOutlined, ExclamationCircleFilled,QuestionCircleOutlined,CheckOutlined } from '@ant-design/icons';
import { Timeline, Input, Button, message, Popover, Modal } from 'antd';
import './index.css';
import { getDateDiff } from '../../../../../utils/tool';
import right from './../../../../../assets/image/right.png';
import { getGoodDetail, orderGood,updateHeat,recallGood,saleTalk,orderCancle,salerMakeSure,orderMakeSure,salerMakeRefuse } from '@/api/index';
const { TextArea } = Input;
const BaseUrl = baseUrl();

export default function GoodDetailModal(props) {
  const [params, setParams] = useState({});//用于保存详情
  const [mineGood, setmineGood] = useState(false);//是否是自己发布的
  const [price, setPrice] = useState();//出价金额
  
  const [endPrice, setEndPrice] = useState(0);//买家确认最后金额
  const [messagesay, setMessagesay] = useState();//留言
  const [orderInfo, setOrderInfo] = useState(false);//是否已经出价
  const [previewVisible, setPreviewVisible] = useState(false);//详情图片的显示
  const [previewImage, setPreviewImage] = useState();//详情图片的显示
  const [orderList, setorderList] = useState();//卖家的买家列表

  useEffect(() => {
    getGoodsDate()
  }, [props.visible]);

  //详情弹窗关闭
  const onClose = () => {
    props.setVisible(false)
    setPrice('')
    setMessagesay('')
    setOrderInfo(false)
    setPreviewVisible(false)
    setmineGood(false)
    setParams({})
  }
  //卖家确定金额
  const salerMakeSureData = async () => {
    // debugger
    const res = await salerMakeSure({
      goodId: props?.Detail?.goodId,
      orderId:orderList[0].orderId,
    })
    if (res?.data?.code == 200) {
      // getGoodsDate()
      props.getCenterList()
      props.setVisible(false)
      message.success(res.data.message)
    }
  }
   //买家确定金额
   const orderMakeSureData = async () => {
    // debugger
    if(endPrice!=0)
    {
      // debugger
    const res = await orderMakeSure({
      goodId: props?.Detail?.goodId,
      finalAmount:endPrice,
    })
    if (res?.data?.code == 200) {
      getGoodsDate()
      message.success(res.data.message)
    }}
    else
    {
      message.error('请先输入金额！')
    }
  }
   //卖家驳回）
   const salerMakeRefuseFun = async () => {
    // debugger
    const res = await salerMakeRefuse({
      goodId: props?.Detail?.goodId,
      orderId:orderList[0].orderId,
    })
    if (res?.data?.code == 200) {
      // getGoodsDate()
      // props.getCenterList()
      props.setVisible(false)
      message.success(res.data.message)
    }
  }
   //买家取消订单
   const orderCancleData = async () => {
    // debugger
    const res = await orderCancle({
      goodId: props?.Detail?.goodId
    })
    if (res?.data?.code == 200) {
      // getGoodsDate()
      props.getCenterList()
      props.setVisible(false)
      message.success(res.data.message)
    }
  }
   //顶一下热度
   const updateHeatData = async () => {
    // debugger
    const res = await updateHeat({
      goodId: props?.Detail?.goodId
    })
    if (res?.data?.code == 200) {
      getGoodsDate()
      message.success(res.data.message)
    }
  }
   //撤回商品
   const recallGooddata = async () => {
    // debugger
    const res = await recallGood({
      goodId: props?.Detail?.goodId
    })
    if (res?.data?.code == 200) {
      props.setVisible(false)
      props.getGoodsList()
      message.success(res.data.message)
    }
  }
   //出售
   const saleTalkFun = async (e) => {
    // debugger
    const res = await saleTalk({
      goodId: props?.Detail?.goodId,
      orderId:e
    })
    if (res?.data?.code == 200) {
      getGoodsDate()
      props.getCenterList()
      message.success(res.data.message)
    }
  }
  //买家出价
  const PostGoodsDate = async () => {
    // debugger
    const res = await orderGood({
      offer: price,
      message: messagesay,
      goodId: props?.Detail?.goodId
    })
    if (res?.data?.code == 200) {
      message.success(res.data.message)
      props.setVisible(false)
      setPrice('')
      setMessagesay('')
    }
  }
  //获取详情
  const getGoodsDate = async () => {
    const res = await getGoodDetail({
      goodId: props?.Detail?.goodId
    })
    if (res?.data?.code == 200) {
      console.log(res.data.detail?.[0], params?.pictureList?.split(','), '111')
      setParams(res.data.detail?.[0])
      if (res.data.mineGood) {
        setmineGood(true)
      }
      else {
        setmineGood(false)
      }
      if (res.data.orderList.length > 0) {
        // debugger
        console.log(res.data.orderList,'dingdanliebia')
        setPrice(res.data.orderList[0]?.offer)
        setMessagesay(res.data.orderList[0]?.message)
        setOrderInfo(true)
        setorderList(res.data.orderList)
      }
      else {
        setPrice('')
        setMessagesay('')
        setOrderInfo(false)
        setorderList([])
      }
    }
  }
  return (
    <>
      {props.visible && (
        <div className='all-page-contain' onClick={onClose.bind(this)}>
          <div
            className='modal-all-box'
            onClick={(e) => e.stopPropagation()}
          >
            <div className='close-button' onClick={onClose.bind(this)} />
            <div>
              <div className='Bg-title'><img className='big-Img' src={BaseUrl + params?.mainPicture} alt="" /></div>

              <div className='line-Img'>详情图片：
                {params?.pictureList?.split(',').map((item) => {
                  if (item) {
                    return <img className='small-Img' src={BaseUrl + item} alt=""
                      onClick={() => {
                        setPreviewVisible(true)
                        setPreviewImage(`${BaseUrl}${item}`)
                      }} />
                  }

                })}

                <Modal
                  visible={previewVisible}
                  // title={previewTitle}
                  footer={null}
                  // width={800}
                  onCancel={() => { setPreviewVisible(false) }}
                  zIndex={999}
                >
                  <img
                    alt="example"
                    style={{
                      width: '100%'
                    }}
                    src={previewImage}
                  />
                </Modal>
              </div>
              <li className='line-Img'>价 &nbsp; 格：&nbsp;<div style={{ color: '#FF0000',display:'inline-block'}}>{params?.price}元
              <div style={{ color: 'rgb(179, 179, 179)',display:'inline-block',fontSize:'16px',textDecoration:'line-through',marginLeft:'10px'}}>{params?.originalPrice}元</div></div></li>
              <li className='line-Img'>议 &nbsp; 价：&nbsp;{params?.lowPrice==0 ? '不议价' :(params?.lowPrice==2 ? '价格再议' : '可小刀')}</li>
              {/* {mineGood?} */}   {!mineGood ?
                <div className='sellKnow'>
                  <li className='sellKnowTitle'><ExclamationCircleFilled style={{ color: '#FCCA00', marginRight: '5px' }} />购买须知</li>

                  <div style={{ color: 'rgba(108, 108, 108, 78)' }}>
                    <li style={{ height: '45px' }}>1.  为减少售后纠纷，与卖家线下交易成功后，需继续完成系统内流程，系统内将保留商品记录。</li>
                    <li style={{ height: '45px' }}>2.  购买商品需保证商品合法，禁止购买触碰法律违规的商品，系统一经检测发现违规违法交易将自动报案，可通过点击<a style={{ color: 'red', borderBottom: '1px solid red' }}>举报</a>按钮举报本商品。</li>
                    <li style={{ height: '45px' }}>3.  如有疑问请联系相关客服：ID64234497（左下角聊天框搜索）</li></div>
                </div> :
                <div className='sellKnow'>
                  <li className='sellKnowTitle'><ExclamationCircleFilled style={{ color: '#FCCA00', marginRight: '5px' }} />出售须知</li>

                  <div style={{ color: 'rgba(108, 108, 108, 78)' }}>
                    <li style={{ height: '45px' }}>1.  为减少售后纠纷，与买家线下交易成功后，需继续完成系统内流程，系统内将保留商品记录。</li>
                    <li style={{ height: '45px' }}>2.  出售商品需保证商品真实且合法，禁止转让触碰法律违规的商品，系统一经检测发现违规违法交易将自动报案，一切责任由商品发布者承担。</li>
                    <li style={{ height: '45px' }}>3.  如有疑问请联系相关客服：ID64234497（左下角聊天框搜索）</li></div>
                </div>}

            </div>

            <div className='rightStyle'>

              <div className='rightTitleAll'> <span className='rightTitle'>
                {params?.goodName}</span><span style={{color:'#9A9A9A',width:'158px',textAlign:'right',lineHeight:'57px'}}>{getDateDiff(params?.updateTime)}</span> </div>
              <div className='detailContent'>&nbsp;&nbsp;{params?.goodDetail}</div>
              {mineGood ? <>{/* 卖家详情界面 */}
                 {params?.goodStatus==0? <Timeline style={{ marginTop: '10px' }}>

                  <Timeline.Item color="green" ><div style={{ color: '#101010' }}>
                    卖家发布（{getDateDiff(params?.publishTime)}）</div></Timeline.Item>
                  {orderList?.map((item, index) => {
                    return <Timeline.Item color="green"><div style={{ color: '#101010' }}>
                      {item.orderName}想要（{getDateDiff(item?.offerTime)}，出价
                      <span style={{ color: 'red', fontSize: '16px' }}>{item?.offer}元</span>）</div>
                      <div className='messageDetail'>{item?.message}</div>
                      <Button type="primary" style={{backgroundColor:'#00B1FD'}} onClick={() => { saleTalkFun(item.orderId) }}>
                        出售
                      </Button>
                    </Timeline.Item>
                  })}

                </Timeline>:''}
                {params?.goodStatus==1? <div className='rightContent'>
                  <img
                    alt=""
                    style={{
                      width: '143px',
                      border:'none'
                    }}
                    src='https://www.donglongdong.xyz/images/upload/1661137464922.png'
                  />
                  <div className='awaitStyle'>请等待买家提交订单信息</div>
                </div>:''}
                {
                params?.goodStatus==2?<div className='endMoney'>
                   <li >最终成交额：<span className='moneyStyle'>{orderList?.[0]?.finalAmount}元</span>
                </li>
                </div>:''
               }
              </> : <>{/* 买家详情界面 */}
              {params?.goodStatus==0? <div >
                    <li >我的出价： <Input
                  placeholder="请输入金额"
                  style={{
                    // background: 'rgba(255, 255, 255,.6)',
                    width: '300px',
                    borderRadius: '12px'
                  }}
                  addonAfter="元"
                  disabled={orderInfo}
                  onChange={(e) =>
                    setPrice(e.target.value)

                  }
                  value={price}
                /></li>
                <div className='detailInput'>&nbsp;留&nbsp;  &nbsp;&nbsp;言：&nbsp; <TextArea
                  rows={4}
                  placeholder="请留言"
                  style={{
                    // background: 'rgba(255, 255, 255,.6)',
                    width: '300px',
                    borderRadius: '12px',
                    marginTop: '30px'
                  }}
                  disabled={orderInfo}
                  onChange={(e) =>
                    setMessagesay(e.target.value)
                  }
                  value={messagesay}
                /></div>
                </div>:''}
                {params?.goodStatus==1? <div className='endMoney'>
                  <li >最终确定金额： <Input
                  placeholder="请输入金额"
                  style={{
                    // background: 'rgba(255, 255, 255,.6)',
                    width: '250px',
                    borderRadius: '12px'
                  }}
                  addonAfter="元"
                  // disabled={orderInfo}
                  onChange={(e) =>
                    setEndPrice(e.target.value)
                  }
                  // value={endPrice}
                />
                 <Popover content={()=>{return   <div>
                                  <p>请输入线下交易最终确认金额，确认订单</p>
                                  <p>信息后将发送到卖家确认，系统内保留订</p>
                                  <p>单，若后续对订单有异议方便溯源</p>
                                </div>}} style={{width:'300px'}} title="">
                    <QuestionCircleOutlined style={{marginLeft:'14px',marginBottom:'5px'}}/>

                  </Popover>
               
                </li>
                </div>:''}
               {
                params?.goodStatus==2?<div className='endMoney'>
                   <li >最终成交额：<span className='moneyStyle'>{orderList?.[0]?.finalAmount}元</span>
                </li>
                </div>:''
               }

              </>}


            </div>
            <div style={{ width: '450px', position: 'absolute', bottom: '80px', right: '20px' }}>
            
            {
              mineGood ?<>{
                params?.goodStatus==0?<div>
                   <Button type="primary"  onClick={() => { updateHeatData() }} style={{ marginBottom: '10px' ,backgroundColor:'#00B1FD'}} block>
                顶一下热度
              </Button>
              <Button type="primary" onClick={() => { recallGooddata() }} danger block>
                撤回商品
              </Button>
                </div>:''
              }
              
                 {params?.goodStatus==2?<div>
                  <Button type="primary"  onClick={() => { salerMakeSureData() }} style={{ marginBottom: '10px' ,backgroundColor:'#00B1FD'}} block>
                  确认订单信息
                </Button>
                <Button type="primary" onClick={() => { salerMakeRefuseFun() }} danger block>
                  驳回
                </Button>
                  </div>:''
                }
              
             </>:<>
            {params?.goodStatus==0?<div>
                 <Button disabled={orderInfo}  type="primary"  onClick={()=>{PostGoodsDate()}} block>
           {orderInfo?'已出价':'我想要'}    
                  </Button>
                </div>:''
              }
              {params?.goodStatus==1?<div>
                <Button type="primary"  onClick={() => { orderMakeSureData() }} style={{ marginBottom: '10px' ,backgroundColor:'#00B1FD'}} block>
                确认订单信息
              </Button>
              <Button type="primary" onClick={() => { orderCancleData() }} danger block>
                取消订单
              </Button>
                </div>:''
              }
               {params?.goodStatus==2?<div>
                <Button type="primary" disabled  onClick={() => { message.warn('请耐心等待哟！') }} style={{height:'39px', marginBottom: '10px',fontSize:'18px' ,color:'white',backgroundColor:'#9A9A9A'}} block>
                等待卖家确认
              </Button>
              <li className='OrderStyle'><img className='Right' src={right} alt="" />  <span style={{height:'39px',fontSize:'18px'}}>买家已确认</span></li>
              {/* <Button type="primary" onClick={() => { orderCancleData() }} danger block>
                取消订单
              </Button> */}
                </div>:''
              }
              </>
            }
           
            </div>

          </div>
        </div>
      )}
    </>
  );
}
